# -*- coding: utf-8 -*-
"""weather.py 获取天气预报信息
"""
from urllib.request import urlopen
from urllib.parse import quote
import gzip
import json
url = "http://wthrcdn.etouch.cn/weather_mini?city="
city = "拉萨"


def main():
    try:
        # 发起网络请求获取数据
        data = urlopen(url + quote(city)).read()
        # 解压缩并解码得到JSON格式字符串
        data_json = gzip.decompress(data).decode()
        # 反序列化为字典对象
        data_dict = json.loads(data_json)
        if data_dict.get("desc") != "OK":
            print("无法获取天气数据！")
        else:  # 输出日期、天气、气温信息
            print("天气预报：" + city)
            forecast = data_dict.get("data").get("forecast")
            for i in forecast:
                date = i.get("date")
                high = i.get("high")
                low = i.get("low")
                weather = i.get("type")
                print("{} {} {} ~ {}".format(date, weather, low, high))
    except Exception as ex:
        print(repr(ex))


if __name__ == "__main__":
    main()
